//
//  BaseController+HXLogin.m
//  RomensBI
//
//  Created by 王增战 on 2017/1/23.
//
//

#import "BaseController+HXLogin.h"
#import "RomensSDK/WebRequestData.h"
#import "ChatDemoHelper.h"
#import "RomensSDK/UIViewController+HUD.h"
#import "HXCommonFiles.h"
#import "TTGlobalUICommon.h"
#import "EMAlertView.h"

@implementation BaseController (HXLogin)
/**
 获取环信的Appkey，初始化SDK

 @param webUrl 中间层访问方法的链接／App的后台的链接的头部
 @param string /handle/unhandle/unloadhandle/...
 @param type 中间层方法的名字
 @param dicParams 参数
 @param key 中间层方法的返回值的字典的key
 @param keyBlock 返回环信的appkey
 */
- (void)HX_GetHXAppkeyByRequest:(NSString *)webUrl apendingString:(NSString *)string queryType:(NSString *)type postData:(id)dicParams ReDicKey:(NSString *)key Block:(void(^)(BOOL isSDKInit))block{
    if (!isEmptyString(key)) {
        [self Request:[webUrl stringByAppendingString:string] queryType:type postData:dicParams success:^(id respone) {
            WebRequestData *data = (WebRequestData *)respone;
            if (data.Error.length >0) {
                [self SHowMessage:data.Error type:showError];
                block(false);
                return;
            }
            if (data.RequestData.length<3) {
                block(false);
                return;
            }
            if ([[ToolHelper JsonToDictionary:data.RequestData] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = [ToolHelper JsonToDictionary:data.RequestData];
                NSString *HX_appKey = [dic objectForKey:key];
                SaveLocalDataForUserDefault(HXAppkey, HX_appKey);
                [[NSNotificationCenter defaultCenter] postNotificationName:HXnotificationName_Register object:@YES];
                block(true);
            }
            block(false);
        }];
    }
}
//获取环信的Appkey，初始化SDK
- (void)HX_GetHXAppkeyByRequest:(NSString *)webUrl
                 apendingString:(NSString *)string
                      queryType:(NSString *)type
                       postData:(id)dicParams
                       ReDicKey:(NSString *)key
                        success:(void(^)(BOOL isSDKInit,id respone))success {
    [self Request:[webUrl stringByAppendingString:string] queryType:type postData:dicParams success:^(id respone) {
        WebRequestData *data = (WebRequestData *)respone;
        if (data.Error.length >0) {
            [self SHowMessage:data.Error type:showError];
            return;
        }
        if (data.RequestData.length<3) {
            return;
        }
        if ([[ToolHelper JsonToDictionary:data.RequestData] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = [ToolHelper JsonToDictionary:data.RequestData];
            NSString *HX_appKey = [dic objectForKey:key];
            SaveLocalDataForUserDefault(HXAppkey, HX_appKey);
            [[NSNotificationCenter defaultCenter] postNotificationName:HXnotificationName_Register object:@YES];
            success(true,data.RequestData);
        }
        success(false,data.RequestData);
    }];
}

#pragma mark -- 环信的登录方法；
- (void)HX_loginWithUsername:(NSString*)username password:(NSString *)password block:(void(^)(void))loginBlock {
    [self HX_loginWithUsername:username password:password animate:false block:^{
        loginBlock();
    }];
}
- (void)HX_loginWithUsername:(NSString*)username password:(NSString *)password block:(void(^)(void))CheckLoginReturnBlock showHud:(BOOL)isSHow {
    if (isSHow) {
        [self showHud:@"数据加载中"];
    }
    
    [self HX_loginWithUsername:username password:password animate:isSHow block:^{
        CheckLoginReturnBlock();
    }];
}
- (void)HX_loginWithUsername:(NSString*)username password:(NSString *)password animate:(BOOL)isSHow block:(void(^)(void))animateBlock{
    if (isSHow) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self showHud:@"数据加载中"];
//        });
    }
    BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;//是否启动自动登录
    if (isAutoLogin){
//        dispatch_async(dispatch_get_main_queue(), ^{
        if (isSHow) {
            [self HiddenHud];
        }
//        });
        animateBlock();
        return;
    }
    EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
    if (!error) {
        [[EMClient sharedClient].options setIsAutoLogin:YES];
        [[EMClient sharedClient] migrateDatabaseToLatestSDK];
//        if (![ChatDemoHelper shareHelper].conversationListVC) {//给单例ChatDemoHelper的属性conversationListVC赋值
//            ConversationListController *conversationC = [[ConversationListController alloc] init];
//            [ChatDemoHelper shareHelper].conversationListVC = conversationC;
//        }
//        [self HX_asynAllData];//此处不加载数据，在切换登录界面的时候在加载数据
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [_self HiddenHud];
//        });
        
    }else {
//        dispatch_async(dispatch_get_main_queue(), ^{
        if (isSHow) {
            [self HiddenHud];
        }
//        });
        
        switch (error.code)
        {
            case EMErrorNetworkUnavailable:
                TTAlert(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                break;
            case EMErrorServerNotReachable:
                TTAlert(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                break;
            case EMErrorUserAuthenticationFailed:
                TTAlert(NSLocalizedString(@"error.usernameOrPasswordIsWrong", @"Username or password is Wrong!"));
                break;
            case EMErrorServerTimeout:
                TTAlert(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                break;
            case EMErrorUserNotFound:
                [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"HXAPPKEY"];
                [EMAlertView showAlertWithTitle:@"系统提示"
                                        message:@"当前企业号与上一次登录的企业号不一致，请在后台关闭程序，重新进入"
                                completionBlock:nil                                                                       cancelButtonTitle:@"确定"
                              otherButtonTitles:nil];
                break;
            default:
                TTAlert(NSLocalizedString(@"login.fail", @"Login failure"));
                break;
        }
        NSLog(@"环信登录失败的原因，%@",error.errorDescription);
    }
    animateBlock();
}
#pragma mark -- 同步数据
- (void)HX_asynInitDataWithGroup:(BOOL)isSync {
    if (isSync == YES) {
        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
    }
    [[ChatDemoHelper shareHelper] asyncConversationFromDB];
    [[ChatDemoHelper shareHelper] asyncPushOptions];
}
- (void)HX_asynInitData {
    [self HX_asynInitDataWithGroup:YES];
}
#pragma mark --
- (ConversationListController *)HX_presentViewController {
    ConversationListController *conversationListC = [[ConversationListController alloc] init];
    //给单例中的对象名指定对象，用于刷新会话列表界面
    [ChatDemoHelper shareHelper].conversationListVC = conversationListC;
    [[ChatDemoHelper shareHelper] asyncConversationFromDB];
    [[ChatDemoHelper shareHelper] asyncPushOptions];
    return conversationListC;
}
#pragma mark -- 环信推出
- (void)HX_logoutActionWithAnimated:(BOOL)animated Block:(void (^)(void))logoutBlock {
    if (animated == YES) {
        __weak BaseController *weakSelf = self;
        [self showHudInView:self.view hint:NSLocalizedString(@"setting.logoutOngoing", @"loging out...")];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            EMError *error = [[EMClient sharedClient] logout:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf hideHud];
                if (error != nil) {
                    [weakSelf showHint:error.errorDescription];
                }
                else{
                    //用户主动退出，取消自动登录---
                    //清除本地环信的appkey
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"HXAPPKEY"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                }
                logoutBlock();
            });
        });
    }else {
        __weak BaseController *weakSelf = self;
        EMError *error = [[EMClient sharedClient] logout:YES];
        if (error != nil) {
            [weakSelf showHint:error.errorDescription];
        }else{
            //用户主动退出，取消自动登录---
            //清除本地环信的appkey
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"HXAPPKEY"];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
        }
        logoutBlock();
    }
}


#pragma mark--获取编码后的UserGUid
- (NSString *)GetUserGuid:(NSString*)username pwd:(NSString*)Pwd{
    
    NSString*pwd=Pwd;
    NSString* newpassword=[ToolHelper md5forX:[pwd stringByAppendingString:@"0"]];
    // NSString*userGuid=[_OrgTextField.text stringByAppendingString:@"|@"];
    NSString*  userGuid=username;
    userGuid=  [[HXSystemOrgGuid stringByAppendingString:@"|@"] stringByAppendingString:[[userGuid stringByAppendingString: @"|@"] stringByAppendingString:newpassword]];
    userGuid=[ToolHelper encodeBase64String:userGuid];
    userGuid= [userGuid stringByReplacingOccurrencesOfString:@"=" withString:@"-"];
    userGuid= [userGuid stringByReplacingOccurrencesOfString:@"+" withString:@"_"];
    return userGuid;
    
}
#pragma mark -- 弃用的接口
- (void)HX_loginWithUsername:(NSString*)username password:(NSString *)password hxAppKey:(NSString *)hxAppKey block:(void (^)(void))CheckLoginReturnBlock{
    [self HX_loginWithUsername:username password:password animate:NO block:^{
        CheckLoginReturnBlock();
    }];
}

//注销(环信的注销方式)
- (void)HX_logoutAction {
    [self HX_logoutActionWithAnimated:YES Block:nil];
}
//注销(环信的注销方式)
- (void)HX_logoutAction:(void (^)(void))logoutBlock  {
    [self HX_logoutActionWithAnimated:YES Block:^{
        logoutBlock();
    }];
}
//通过中间层方法，获取环信的key，然后初始化SDK
- (void)HX_GetHXAppkeyWithWebURL:(NSString *)webUrl
                  apendingString:(NSString *)string
                       queryType:(NSString *)type
                        postData:(id)dicParams
                        ReDicKey:(NSString *)key
                           Block:(void(^)(NSString *appkey))keyBlock {
    if (!isEmptyString(key)) {
        [self Request:[webUrl stringByAppendingString:string] queryType:type postData:dicParams success:^(id respone) {
            WebRequestData *data = (WebRequestData *)respone;
            if (data.Error.length >0) {
                [self SHowMessage:data.Error type:showError];
                return;
            }
            if (data.RequestData.length<3) {
                return;
            }
            NSMutableDictionary *dic = [ToolHelper JsonToDictionary:data.RequestData];
            NSString *HX_appKey = [dic objectForKey:key];
            SaveLocalDataForUserDefault(HXAppkey, HX_appKey);
            [[NSNotificationCenter defaultCenter] postNotificationName:HXnotificationName_Register object:@YES];
            keyBlock(HX_appKey);
        }];
    }
}


@end
